<!-- 新增与编辑门店 -->
<template>
  <el-dialog
    :title="dialog.title"
    :visible.sync="dialog.show"
    width="530px"
    height="400px"
    custom-class="mydialog"
    append-to-body
    @close="handleClose"
  >
    <div class="dialog-content">
      <el-form ref="form1" :model="form" :rules="rules" label-width="150px">
        <el-form-item prop="name" label="门店名称：">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="店长姓名：">
          <el-autocomplete
            v-model="form.person"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="门店地址：">
          <el-input v-model="form.address"/>
        </el-form-item>
        <el-form-item label="门店面积：" prop="area">
          <el-input v-model="form.area"/>
        </el-form-item>
        <el-form-item label="门店等级：">
          <el-select v-model="form.level" placeholder="请选择" class="seach-select" size="small">
            <el-option
              v-for="item in form.level_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="服务星号：" >
          <el-input v-model="form.start"/>
        </el-form-item>-->
        <el-form-item prop="type" label="发货仓：">
          <el-autocomplete
            v-model="form.type"
            :fetch-suggestions="querySearchAsyncWarehouse"
            placeholder="请输入内容"
            @select="handleSelectWarehouse"
          />
        </el-form-item>
      </el-form>
      <div class="text-center mt-30">
        <el-button class="greenbt bt-wd" type="primary" @click="saveFun('form1')">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import {
  getUserByName,
  saveStore,
  updateStore,
  queryWarehouseByWarehouseName
} from '@/api/pas/shop'
var checkArea = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const regu = /^[0-9]+(\.[0-9]{1,2})?$/
    const rsCheck = regu.test(value)
    if (!rsCheck) {
      return callback(new Error('格式不正确'))
    }
  }
  callback()
}

export default {
  props: {
    // 父组件调用时传进来的参数
    modalStaticData: {
      type: Object,
      default: () => {}
    },
    modalData: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    return {
      dialog: {
        title: '',
        show: true
      },
      form: {
        // start: '',
        name: '',
        person: '',
        address: '',
        level: '',
        level_options: [],
        personObj: null,
        warehouseObj: null,
        type: '',
        area: ''
      },
      rules: {
        name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择发货仓', trigger: 'focus' }],
        area: [
          {
            required: true,
            validator: checkArea,
            trigger: 'blur'
          }
        ]
      },
      // start
      userList: [],
      state: '',
      warehouseList: []
      // end
    }
  },
  mounted() {
    const storeLevlList = [
      { label: '直营-A', value: '直营-A' },
      { label: '直营-B', value: '直营-B' },
      { label: '直营-C', value: '直营-C' },
      { label: '加盟', value: '加盟' }
    ]
    this.form.level_options = storeLevlList
    getUserByName('').then(res => {
      this.userList = res.data.data
      for (var i = 0; i < this.userList.length; i++) {
        this.userList[i].value = this.userList[i].loginName
      }
    })

    queryWarehouseByWarehouseName('').then(res => {
      this.warehouseList = res.data.data
      for (var i = 0; i < this.warehouseList.length; i++) {
        this.warehouseList[i].value = this.warehouseList[i].warehouseName
      }
    })

    if (this.modalData.type !== 'edict') {
      this.dialog.title = '门店添加'
    } else {
      this.getWarehouseInWhere(this.modalData.data.warehouseName)
      this.getUserInWhere(this.modalData.data.storeManagerName)
      this.dialog.title = '门店编辑'
      this.form.name = this.modalData.data.storeName
      this.form.person = this.modalData.data.storeManagerName
      this.form.address = this.modalData.data.storeAddress
      this.form.area = this.modalData.data.storeArea
      this.form.level = this.modalData.data.storeLevel
      this.form.type = this.modalData.data.warehouseName
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    saveFun(formName) {
      const self = this
      console.warn('进入saveFun方法')
      self.$refs[formName].validate(valid => {
        if (valid) {
          const formData = new FormData()
          console.warn('1234')
          console.warn(this.form.warehouseObj)
          if (this.form.warehouseObj !== null) {
            formData.append('warehouseId', this.form.warehouseObj.warehouseId)
          }
          if (this.form.personObj != null) {
            formData.append('storeManagerName', this.form.personObj.loginName.trim())
            // formData.append(
            //   'storeManagerAccount',
            //   this.form.personObj.loginName.trim()
            // )
            formData.append(
              'storeManagerPhone',
              this.form.personObj.mobile.trim()
            )
            formData.append('storeManager', this.form.personObj.id.trim())
          }
          formData.append('storeName', this.form.name.trim())
          formData.append('storeAddress', this.form.address.trim())
          formData.append('storeArea', this.form.area ? this.form.area : '')
          formData.append('storeLevel', this.form.level.trim())
          if (this.modalData.type !== 'edict') {
            // 新增
            console.log('warehouseName' + formData.get('warehouseName'))
            saveStore(formData)
              .then(res => {
                console.warn(res)
                if (res.data.status === 'faild') {
                  this.$message.error(res.data.messge)
                } else {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  })
                }
              })
              .finally(() => {
                this.dialog.show = false
                this.modalStaticData.closeChildAndRefresh()
              })
          } else {
            // 修改
            console.log('进入修改')
            console.warn(this.form.person)
            console.warn(this.form.type)
            formData.append('storeId', this.modalData.data.storeId)
            console.log('storeId' + formData.get('storeId'))
            updateStore(formData)
              .then(res => {
                console.log(res)
                if (res.data.status === 'faild') {
                  this.$message.error(res.data.messge)
                } else {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                }
              })
              .finally(() => {
                this.dialog.show = false
                this.modalStaticData.closeChildAndRefresh()
              })
          }
        } else {
          return false
        }
      })
    },
    /**
       * 选中交互(用户)
       */
    handleSelect(item) {
      console.warn(item)
      this.form.personObj = item
      console.warn(this.form.personObj)
    },
    /**
       * 选中交互(仓库)
       */
    handleSelectWarehouse(item) {
      console.warn(item)
      this.form.warehouseObj = item

      console.warn(this.form.warehouseObj)
    },
    /**
       * 下拉框(用户)
       */
    querySearchAsync(queryString, cb) {
      this.getUserInWhere(queryString)
      var userList = this.userList
      var results = queryString
        ? userList.filter(this.createStateFilter(queryString))
        : userList
      cb(results)
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.value ? state.value.indexOf(queryString) === 0 : false
        )
      }
    },
    /**
       * 下拉框(仓库)
       */
    querySearchAsyncWarehouse(queryString, cb) {
      this.getWarehouseInWhere(queryString)
      var warehouseList = this.warehouseList
      var results = queryString
        ? warehouseList.filter(this.createStateFilterWarehouse(queryString))
        : warehouseList
      cb(results)
    },
    createStateFilterWarehouse(queryString) {
      return state => {
        return (
          state.value ? state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0 : false
        )
      }
    },
    getWarehouseInWhere(queryString) {
      queryWarehouseByWarehouseName(queryString).then(res => {
        if (res.data.data[0] !== null) {
          this.form.warehouseObj = res.data.data[0]
        }
      })
    },
    getUserInWhere(queryString) {
      getUserByName(queryString).then(res => {
        if (res.data.data[0] !== null) {
          this.form.personObj = res.data.data[0]
        }
      })
    }
  }
}
</script>
